﻿using System.Text;
using System.Windows;
using PengSW.WindowHelper;

namespace UdpToolkit
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            _Model = new MainModel();
            string[] aHistories = Properties.Settings.Default.History.Split('|');
            foreach (var aHistory in aHistories) _Model.SendHistory.Add(aHistory);
            this.DataContext = _Model;
        }

        private readonly MainModel _Model;

        private void OnSend_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            this.Exec(_Model.Send);
        }

        private void OnSend_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.CanSend ?? false;
        }

        private void OnStartListen_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            this.Exec(_Model.StartListen);
        }

        private void OnStartListen_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.CanStartListen ?? false;
        }

        private void OnStopListen_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            this.Exec(_Model.StopListen);
        }

        private void OnStopListen_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.CanStopListen ?? false;
        }

        private void OnGetFreePort_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            this.Exec(_Model.GetFreePort);
        }

        private void OnGetFreePort_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.CanGetFreePort ?? false;
        }

        private void OnWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            StringBuilder aStringBuilder = new StringBuilder();
            foreach (var aHistory in _Model.SendHistory)
            {
                if (aStringBuilder.Length > 0) aStringBuilder.Append("|");
                aStringBuilder.Append(aHistory);
            }
            Properties.Settings.Default.History = aStringBuilder.ToString();
            Properties.Settings.Default.Save();
        }
    }
}
